/**
 * Copyright &copy; 2012-2016 <a href="https://istep.lczyfz.com">Istep</a> All rights reserved.
 */
package com.lczyfz.istep.modules.scene.web;

import com.lczyfz.istep.common.config.Global;
import com.lczyfz.istep.common.persistence.Page;
import com.lczyfz.istep.common.utils.StringUtils;
import com.lczyfz.istep.common.web.BaseController;
import com.lczyfz.istep.modules.openstack.api.neutron.impl.NetworksImpl;
import com.lczyfz.istep.modules.openstack.api.neutron.impl.SubnetImpl;
import com.lczyfz.istep.modules.openstack.api.neutron.impl.SubnetPoolImpl;
import com.lczyfz.istep.modules.openstack.api.neutron.model.Subnet;
import com.lczyfz.istep.modules.openstack.api.neutron.model.SubnetPool;
import com.lczyfz.istep.modules.scene.entity.SceneNetwork;
import com.lczyfz.istep.modules.scene.entity.SceneSubnet;
import com.lczyfz.istep.modules.scene.service.SceneNetworkService;
import com.lczyfz.istep.modules.scene.service.SceneSubnetService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 网络管理Controller
 * @author dh
 * @version 2017-03-20
 */
@Controller
@RequestMapping(value = "${adminPath}/scene/sceneNetwork")
public class SceneNetworkController extends BaseController {

	@Autowired
	private SceneNetworkService sceneNetworkService;
	@Autowired
	private SceneSubnetService sceneSubnetService;
	@ModelAttribute
	public SceneNetwork get(@RequestParam(required=false) String id) {
		SceneNetwork entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = sceneNetworkService.get(id);
		}
		if (entity == null){
			entity = new SceneNetwork();
		}
		return entity;
	}
	
	@RequiresPermissions("scene:sceneNetwork:view")
	@RequestMapping(value = {"list", ""})
	public String list(SceneNetwork sceneNetwork, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<SceneNetwork> page = sceneNetworkService.findPage(new Page<SceneNetwork>(request, response), sceneNetwork); 
		model.addAttribute("page", page);
		return "modules/scene/sceneNetworkList";
	}

	@RequiresPermissions("scene:sceneNetwork:view")
	@RequestMapping(value = "form")
	public String form(SceneNetwork sceneNetwork, Model model,String type) {
		List<SubnetPool> spList=new ArrayList<>();
		try{
			SubnetPoolImpl subnetPool = new SubnetPoolImpl();
			logger.debug("获取子网池");
			spList = subnetPool.getSubnetPools();
		}catch (RuntimeException e){

		}

		model.addAttribute("spList", spList);

		model.addAttribute("sceneNetwork", sceneNetwork);
		model.addAttribute("type", type);
		logger.debug("type=== [{}]", type);
		return "modules/scene/sceneNetworkForm";
	}

	@RequiresPermissions("scene:sceneNetwork:edit")
	@RequestMapping(value = "save")
	public String save(SceneNetwork sceneNetwork,SceneSubnet sceneSubnet, Model model, RedirectAttributes redirectAttributes,String subnetCreate,String type,String networkAddressSelect) {
		logger.debug("subnetName=== [{}]", sceneNetwork.getNetworkName());
		logger.debug("subnetName===type [{}]", type+sceneNetwork.getId());
		logger.debug("subnetName=== [{}]", sceneSubnet.getSubnetName() + " " + sceneSubnet.getSubnetpoolId() + " " + sceneSubnet.getIpVersion());
		logger.debug("是否创建子网=== [{}]", subnetCreate);
		logger.debug("网络选择=== [{}]", networkAddressSelect);

		if(sceneNetworkService.get(sceneNetwork)==null)
		{
			logger.debug("插入！");

			List<SceneNetwork> sceneNetworks=sceneNetworkService.getNetworkByName(sceneNetwork);
			if(sceneNetworks.size()>0)
			{
				addMessage(redirectAttributes, "保存网络'"+sceneNetwork.getNetworkName()+"'失败，该网络已存在");
				return "redirect:"+Global.getAdminPath()+"/scene/sceneNetwork/?repage";

			}else {
				//不实际创建os网络
				sceneNetworkService.save(sceneNetwork);

				if(subnetCreate.equals("0"))
				{

					sceneSubnet.setNetworkId(sceneNetwork.getId());
					if(networkAddressSelect.equals("1"))
					{
						sceneSubnet.setSubnetpoolId(null);
					}else {
						sceneSubnet.setCidr(null);
					}

					sceneSubnetService.save(sceneSubnet);
					logger.debug("===dingh===保存子网成功！");

					addMessage(redirectAttributes, "保存网络成功");
				}


//				//调用os保存网络接口
//				try{
//					NetworksImpl networkDemo=new NetworksImpl();
//					Network nw=new Network();
//					nw.setName(sceneNetwork.getNetworkName());
//					Network nwCreat=networkDemo.createNetwork(nw);
//					logger.debug("networkId=== [{}]", nwCreat.getId());
//
//					SceneNetwork network=new SceneNetwork();
//
////				String netId = IdGen.uuid();
//					network.setId(nwCreat.getId());
//					network.setNetworkStatus(nwCreat.getStatus());
//					network.setNetworkName(nwCreat.getName());
//					logger.debug("networkId=== [{}]", network.getId());
//
////				sceneNetwork.setNetworkStatus(network.getStatus());
//					logger.debug("networkId1a=== [{}]", network.getId());
//
////				network.setIsNewRecord(true);
////				sceneNetworkService.save(network);
//
//					sceneNetworkService.networkPreInsert(network);
//					sceneNetworkService.insert(network);
//					logger.debug("networkId2a=== [{}]", network.getId());
//
//					if(subnetCreate.equals("0"))
//					{
//
//						SubnetImpl subnetImpl= new SubnetImpl();
//						Subnet sntt = new Subnet();
//						logger.debug("subnetId=== [{}]", sceneSubnet.getSubnetName() + " " + nwCreat.getId() + " " + sceneSubnet.getIpVersion() + " " + sceneSubnet.getSubnetpoolId() + " ");
//
//						sntt.setsubnetName(sceneSubnet.getSubnetName());
//						sntt.setsubnetNetworkId(nwCreat.getId());
//						sntt.setsubnetIpVersion(sceneSubnet.getIpVersion());
//						if(networkAddressSelect.equals("1"))
//						{
//							sntt.setsubnetCidr(sceneSubnet.getCidr());
//						}else {
//							sntt.setsubnetPoolId(sceneSubnet.getSubnetpoolId());
//						}
//
//						Subnet sn_new = subnetImpl.createSubnet(sntt);
////					String subnetId = IdGen.uuid();
//						logger.debug("subnetId=== [{}]", sn_new.toString());
//						logger.debug("networkId=== [{}]", sn_new.getsubnetId());
//
//						SceneSubnet subnet=new SceneSubnet();
//						subnet.setId(sn_new.getsubnetId());
//						subnet.setSubnetName(sn_new.getsubnetName());
//						subnet.setNetworkId(sn_new.getsubnetNetworkId());
//						subnet.setIpVersion(sn_new.getsubnetIpVersion());
//						subnet.setSubnetpoolId(sn_new.getsubnetPoolId());
//						subnet.setCidr(sn_new.getsubnetCidr());
//						subnet.setGatewayIp(sn_new.getsubnetGatewayIp());
//						subnet.setTenantId(sn_new.getsubnetTenantId());
//						subnet.setProjectId(sn_new.getsubnetProjectId());
//
//						logger.debug("subnetId=== [{}]", subnet.getId());
//
//						sceneSubnetService.preInsert(subnet);
//						sceneSubnetService.insert(subnet);
//
//						logger.debug("subnetId=== [{}]", subnet.getId());
//						addMessage(redirectAttributes, "保存网络成功");
//					}
//				}catch (RuntimeException e){
//					addMessage(redirectAttributes, "保存网络失败");
//				}



			}
		}else {
			logger.debug("修改！");
			sceneNetworkService.save(sceneNetwork);

//			try{
//				NetworksImpl networkDemo=new NetworksImpl();
//				Network network=new Network();
//				network.setName(sceneNetwork.getNetworkName());
//				networkDemo.updateNetwork(sceneNetwork.getId(),network);
//				sceneNetworkService.save(sceneNetwork);
//				addMessage(redirectAttributes, "修改网络成功");
//			}catch (RuntimeException e){
//				addMessage(redirectAttributes, "修改网络失败");
//
//			}


		}


		return "redirect:"+Global.getAdminPath()+"/scene/sceneNetwork/?repage";
	}
	
	@RequiresPermissions("scene:sceneNetwork:edit")
	@RequestMapping(value = "delete")
	public String delete(SceneNetwork sceneNetwork, RedirectAttributes redirectAttributes) {

		try{
			NetworksImpl networkDemo=new NetworksImpl();
			networkDemo.deleteNetwork(sceneNetwork.getId());
			SceneSubnet sceneSubnet=new SceneSubnet();
			sceneSubnet.setNetworkId(sceneNetwork.getId());
			sceneSubnetService.deleteByNetworkId(sceneSubnet);
			sceneNetworkService.delete(sceneNetwork);
			addMessage(redirectAttributes, "删除网络成功");
		}catch (RuntimeException e){
			addMessage(redirectAttributes, "删除网络失败");
		}

		return "redirect:"+Global.getAdminPath()+"/scene/sceneNetwork/?repage";
	}

	//根据子网池id获取ip版本
	@ResponseBody
	@RequestMapping(value = "getIPversion")
	public String getIPversion(@RequestParam(required = false) String subnetPoolId) {
		logger.debug("==dingh==" + subnetPoolId);

		return "6";
	}

	/**
	 * 查看网络子网列表
	 */
	@ResponseBody
	@RequestMapping(value = "getSubnetList")
	public List<SceneSubnet> getSubnetList(@RequestParam(required = false) String ids) {
		SceneSubnet sceneSubnet=new SceneSubnet();
		sceneSubnet.setNetworkId(ids);
		return sceneSubnetService.findList(sceneSubnet);
	}

	@RequiresPermissions("scene:sceneRouter:view")
	@RequestMapping(value ="subnetManage")
	public String subnetManage(SceneNetwork sceneNetwork, HttpServletRequest request, HttpServletResponse response, Model model) {

//		Page<SceneRouter> page = sceneRouterService.findPage(new Page<SceneRouter>(request, response), sceneRouter);
		SceneSubnet sceneSubnet=new SceneSubnet();
		sceneSubnet.setNetworkId(sceneNetwork.getId());
		Page<SceneSubnet> page = sceneSubnetService.findPageByNetworkId(new Page<SceneSubnet>(request, response), sceneSubnet);
		model.addAttribute("page", page);
		model.addAttribute("sceneNetwork", sceneNetwork);

		logger.debug("page=== [{}]", page.getList().size());

		return "modules/scene/sceneNetworkSubnetList";
	}

	@RequestMapping(value ="deleteSubnet")
	public String deleteSubnet(String subnetId,String networkId, Model model,  RedirectAttributes redirectAttributes,HttpServletRequest request, HttpServletResponse response) {

		SubnetImpl subnetImpl= new SubnetImpl();
		subnetImpl.deleteSubnet(subnetId);


		SceneSubnet sceneSubnet=new SceneSubnet();
		sceneSubnet.setId(subnetId);
		logger.debug("page=== [{}]", subnetId+" "+networkId);

		sceneSubnetService.delete(sceneSubnet);

		SceneSubnet sceneSubnet1=new SceneSubnet();
		sceneSubnet1.setNetworkId(networkId);
		Page<SceneSubnet> page = sceneSubnetService.findPageByNetworkId(new Page<SceneSubnet>(request, response), sceneSubnet1);
		model.addAttribute("page", page);
		addMessage(redirectAttributes, "删除子网成功");
		return "modules/scene/sceneNetworkSubnetList";

	}

	@RequiresPermissions("scene:sceneNetwork:view")
	@RequestMapping(value = "createSubnet")
	public String createSubnet(SceneNetwork sceneNetwork, Model model) {
		logger.debug("获取子网池");
		SubnetPoolImpl subnetPool = new SubnetPoolImpl();
		List<SubnetPool> spList = subnetPool.getSubnetPools();
		for(SubnetPool sp : spList){
			System.out.println(sp.getSpId()+" "+sp.getSpName() + " "+sp.getSpProjectId()+" "+sp.getSpTenantId()+" "+sp.getSpPrefixes().get(0)+" "+sp.getSpIsDefault()+"||"+
					sp.getSpIpVersion()+" "+sp.getSpDefaultPrefixlen());
		}
		model.addAttribute("spList", spList);
		model.addAttribute("sceneNetwork", sceneNetwork);
		return "modules/scene/sceneNetworkCreatSubnet";
	}

	/**
	 * 保存子网
	 * @param sceneNetwork
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("scene:sceneRouter:view")
	@RequestMapping(value ="saveSubnet")
	public String saveSubnet(SceneNetwork sceneNetwork,SceneSubnet sceneSubnet, HttpServletRequest request, HttpServletResponse response, Model model) {

		SubnetImpl subnetImpl= new SubnetImpl();
		Subnet sntt = new Subnet();
		logger.debug("subnetId=== [{}]", sceneSubnet.getSubnetName()+" "+sceneNetwork.getId()+" "+sceneSubnet.getIpVersion()+" "+sceneSubnet.getSubnetpoolId()+" ");

		sntt.setsubnetName(sceneSubnet.getSubnetName());
		sntt.setsubnetNetworkId(sceneNetwork.getId());
		sntt.setsubnetIpVersion(sceneSubnet.getIpVersion());
		sntt.setsubnetPoolId(sceneSubnet.getSubnetpoolId());
		Subnet sn_new = subnetImpl.createSubnet(sntt);
//					String subnetId = IdGen.uuid();
		logger.debug("subnetId=== [{}]", sn_new.toString());

		SceneSubnet subnet=new SceneSubnet();
		subnet.setId(sn_new.getsubnetId());
		subnet.setSubnetName(sn_new.getsubnetName());
		subnet.setNetworkId(sn_new.getsubnetNetworkId());
		subnet.setIpVersion(sn_new.getsubnetIpVersion());
		subnet.setSubnetpoolId(sn_new.getsubnetPoolId());
		subnet.setCidr(sn_new.getsubnetCidr());
		subnet.setGatewayIp(sn_new.getsubnetGatewayIp());
		subnet.setTenantId(sn_new.getsubnetTenantId());
		subnet.setProjectId(sn_new.getsubnetProjectId());
		sceneSubnetService.preInsert(subnet);
		sceneSubnetService.insert(subnet);


//		String subnetId = IdGen.uuid();
//		SceneSubnet subnet=new SceneSubnet();
//		subnet.setId(subnetId);
//		subnet.setSubnetName(sceneSubnet.getSubnetName());
//		subnet.setNetworkId(sceneNetwork.getId());
//		subnet.setIpVersion(sceneSubnet.getIpVersion());
//		subnet.setSubnetpoolId(sceneSubnet.getSubnetpoolId());
//		sceneSubnetService.insert(subnet);

//		Page<SceneRouter> page = sceneRouterService.findPage(new Page<SceneRouter>(request, response), sceneRouter);
		SceneSubnet pageSubnet=new SceneSubnet();
		pageSubnet.setNetworkId(sceneNetwork.getId());
		Page<SceneSubnet> page = sceneSubnetService.findPageByNetworkId(new Page<SceneSubnet>(request, response), pageSubnet);
		model.addAttribute("page", page);
		model.addAttribute("sceneRouter", sceneNetwork);
		logger.debug("saveSubnet=== [{}]", sceneNetwork.getId());
		logger.debug("page=== [{}]", page.getList().size());

		return "modules/scene/sceneNetworkSubnetList";
	}
}